package com.jay.lang.clazz.thread;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * This is an example of how a TimerTask may be employed to cause an application
 * to wait for an external process to terminate for for no longer than thirty
 * seconds.
 * 
 * This is a simple example program. It will run and it demonstrates an
 * interesting point but if you copy and paste this code directly into an
 * application and expect that nothing bad is going to happen, doom on you.
 * 
 * @author Kyle W. Cartmell
 */
public class ProcessTimeoutExample {

	public static void main(String[] args) throws IOException {
		Timer timer = null;
		Process p = null;
		try {
			timer = new Timer(true);
			InterruptTimerTask interrupter = new InterruptTimerTask(
					Thread.currentThread());
			timer.schedule(interrupter, 30 /* seconds */* 1000 /*
																 * milliseconds
																 * per second
																 */);
			p = Runtime.getRuntime().exec("C:\\windows\\notepad.exe");
			p.waitFor();
		} catch (InterruptedException e) {
			// do something to handle the timeout here
			p.destroy();
		} finally {
			timer.cancel(); // If the process returns within the timeout period,
							// we have to stop the interrupter
							// so that it does not unexpectedly interrupt some
							// other code later.

			Thread.interrupted(); // We need to clear the interrupt flag on the
									// current thread just in case
									// interrupter executed after waitFor had
									// already returned but before timer.cancel
									// took effect.
									//
									// Oh, and there's also Sun bug 6420270 to
									// worry about here.
		}
	}

}

/**
 * Just a simple TimerTask that interrupts the specified thread when run.
 */
class InterruptTimerTask extends TimerTask {

	private Thread thread;

	public InterruptTimerTask(Thread t) {
		this.thread = t;
	}

	public void run() {
		thread.interrupt();
	}

}
